package com.yanqu.road.web.controller.usercenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.servercenter.AppKeyInfo;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;

@WebServlet(urlPatterns = "/platformQueryRoles")
public class PlatformQueryRoles extends BaseJsonHttpServlet {
    private static Logger logger = LogManager.getLogger(PlayerRoleQuery.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.info("request platformQueryRoles");
        HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
        JSONObject paramObj = httpJsonWebParam.getParamObj();
        JSONArray queryArray;
        try{
            queryArray = paramObj.getJSONArray("data");
        }catch (Exception e){
            logger.error("platformQueryRoles argument error:" + e);
            sendResult(response, 0, "argument error");
            return;
        }

        JSONObject result = getResultObj(1, "success");
        JSONArray roleList = new JSONArray();
        List<Future> futureList = new ArrayList<>();
        ExecutorService webExecutor = WebServer.getWebExecutor();
        for (Object jo : queryArray) {
            JSONObject queryObj = (JSONObject) jo;
            String openId = queryObj.getString("userID");
            long serverId = queryObj.getLongValue("serverId");
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
            if (serverInfo == null) {
                continue;
            }

            String roleInfo = "";
            try {
                JSONObject queryServerObj = new JSONObject();
                queryServerObj.put("userID", openId);
                SortedMap<String, String> paramMap = SignHelper.getParamMap(queryServerObj);
                AppKeyInfo appKeyInfo = AppKeyMgr.getAppKeyInfo(serverId);
                if(null == appKeyInfo){
                    continue;
                }
                String sign = SignHelper.getSign(paramMap, appKeyInfo.getAndroidAppSecret());
                queryServerObj.put("sign", sign);

                Future future = webExecutor.submit(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        String roleInfo = "";
                        try {
                            roleInfo = HttpHelper.doPostJsonTimeOut(serverInfo.getWebServerUrl() + "/queryUser", queryServerObj.toJSONString(), "UTF-8", new HashMap<>());
                            JSONObject jsonObject = JSONObject.parseObject(roleInfo);
                            if (jsonObject.getIntValue("state") == 1) {
                                JSONArray jsonArray = JSONArray.parseArray(jsonObject.getJSONObject("data").getString("roleList"));
                                for (Object obj : jsonArray) {
                                    // 写入服务器id
                                    ((JSONObject) obj).put("serverId", serverId);
                                }
                                synchronized (roleList) {
                                    roleList.addAll(jsonArray);
                                }
                            }
                        } catch (Exception ex) {
                            logger.error("json Array parse error, {} {}", roleInfo, ex.toString());
                        }
                        return true;
                    }
                });
                futureList.add(future);
            } catch (Exception ex) {
                logger.error("json Array parse error, {} {}", roleInfo, ex.toString());
            }

        }
        if(!futureList.isEmpty()) {
            for (Future future : futureList) {
                try {
                    boolean ret = (boolean) future.get(2, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roleList", roleList);
        result.put("data", jsonObject);
        sendMessage(response, result.toJSONString());
    }
}
